﻿using System;
using System.Collections.Generic;

using System.Text;

using Xeno.Core;
using Xeno.Module;
using OpenTK;
namespace Xeno.Physics
{
     public class XenoMeshCollider : XenoCollider
    {

        public IntPtr _Data { get; set; }
        float[] verts;
        int[] indices;
        IntPtr vp, tp;
        unsafe void* vap;
        unsafe void* tap;
        public XenoMeshCollider(string name, XenoNode attached)
            : base(name, attached)
        {
            Attached = attached;

            List<XenoNode> meshes = attached.AllWithType(typeof(XenoMesh), null);

            XenoMesh msh = meshes[0].Mesh;

            XenoDebug.AssertNull(msh, "XenoMeshCollider.ctor()");

            
            //XenoMesh msh = Attached.Mesh;
            verts = new float[msh.Vertices.Count * 3];
            indices = new int[msh.Triangles.Count * 3];

            for (int i = 0; i < msh.Vertices.Count; i++)
            {
                XenoVertex v = msh.Vertices[i];
                Matrix4 pose = attached.WorldMatrix;
                Vector3 transformed = Vector3.TransformPosition(v.Position, pose);
                verts[i * 3] = transformed.X;
                verts[i * 3 + 1] = transformed.Y;
                verts[i * 3 + 2] = transformed.Z;
            }
            for (int i = 0; i < msh.Triangles.Count; i++)
            {
                XenoTriangle t = msh.Triangles[i];
                indices[i * 3] = t.V1;
                indices[i * 3 + 2] = t.V2;
                indices[i * 3 + 1] = t.V3;

            }


            List<XenoNode> managers = Attached.GraphOwner.RootNode.AllWithType(typeof(XenoPhysicsManager), null);
            XenoNode man = managers[0];

            unsafe
            {
                fixed (void *va = verts)
                {
                    vap = va;
                    fixed (void * ta = indices)
                    {
                        tap = ta;
                        vp = new IntPtr(vap);
                        tp = new IntPtr(tap);
                        Shape = XP.ShapeMesh(vp, tp, msh.Vertices.Count, msh.Triangles.Count);
                        System.Diagnostics.Debug.WriteLine("MeshShape= " + Shape.ToString());

                        ShapeMap[XP.GetActor(Shape)] = attached;

                    }
                }
            }


        }

    }
}
